package cn.shangtour.user.service;

import java.util.UUID;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.fasterxml.jackson.databind.ObjectMapper;

import cn.shangtour.common.pojo.User;
import cn.shangtour.common.utils.MD5Util;
import cn.shangtour.common.utils.MapperUtil;
import cn.shangtour.user.mapper.UserMapper;
import redis.clients.jedis.JedisCluster;

@Service
public class UserService {
	@Autowired
	private UserMapper userMapper;
	public Integer checkUsername(String passport) {
		return userMapper.checkUsername(passport);
	}
	
	public void userSave(User user) {
		user.setUserId(UUID.randomUUID().toString());
		user.setUserNickname("测试用户");
		user.setUserPassword(MD5Util.md5(user.getUserPassword()));
		userMapper.userSave(user);
	}

	public void setPassword(User user) {
		// TODO Auto-generated method stub
		user.setUserId("77e85773-e190-4b02-b2f9-58e7cbd05066");
		
		userMapper.setPassword(user);
	}
	
	
	
	private ObjectMapper mapper=MapperUtil.MP;
	
	@Autowired
	private JedisCluster jedis;
	
	public String doLogin(User user) {
		try {
			user.setUserPassword(MD5Util.md5(user.getUserPassword()));
			
			User exist = userMapper.queryUserByNameAndPassword(user);
			if(exist==null){
				return "";
			}else{
				String ticket = UUID.randomUUID().toString();
				String userJson;
					userJson=mapper.writeValueAsString(exist);
					
				String existTicket = jedis.get("user_logined_"+exist.getUserId());
				if(StringUtils.isNotEmpty(existTicket)){
					jedis.del(existTicket);
				}
				jedis.setex("user_logined_"+exist.getUserId(), 60*30, ticket);
				jedis.setex(ticket, 60*30, userJson);
				return ticket;
			}
		} catch (Exception e) {
			e.printStackTrace();
			return "";
		}
	}

	public String queryUserJson(String ticket) {
		String userJson="";
		try {
			Long leftTime = jedis.pttl(ticket);
			if(leftTime<1000*60*101){
				jedis.pexpire(ticket, leftTime+1000*60*5);
				
			}
			userJson=jedis.get(ticket);
			return userJson;
			
		} catch (Exception e) {
			e.printStackTrace();

		return "";
		}
	}

	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
		
	
}
